package com.netsdk.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.URL;
import java.util.Dictionary;

/**
 * 文件工具类
 *
 * @author Yan Xu
 * @version 1.0
 * @date 2021/8/7
 * Copyright © goodits
 */
@Slf4j
public class FilePathUtils {
    private static final String DIR_PATH = "static/img";

    public static String getUploadDir(){
        ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader();
        if(ObjectUtils.isEmpty(defaultClassLoader)){
            log.warn("获取类加载器失败失败");
            return null;
        }
        URL resource = defaultClassLoader.getResource(DIR_PATH);
        if(ObjectUtils.isEmpty(resource)){
            log.warn("获取url资源失败");
            return null;
        }
        //上传目录地址
        String uploadDir = resource.getPath();;
        //如果目录不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if(!dir.exists())
        {
            boolean mkdir = dir.mkdir();
            if(Boolean.FALSE.equals(mkdir)){
                log.warn("创建目录{}失败",uploadDir);
                return null;
            }
        }
        return uploadDir;
    }

   public static String getUrlPathByFileName(HttpServletRequest request, String fileName){
       return request.getScheme()+"://"+request.getServerName()+":"+
               request.getServerPort()+"/img/"+fileName;
    }
}
